import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, DatePicker, Empty, Form, Icon, Input, Row, message } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import moment from 'moment';
import { formatDateRange } from '@/utils/utils';
import FormContainer from './FormContainer';
import styles from './index.less';

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

/**
 * 员工档案 - 培训经历
 */
const TrainingExperienceSection = ({ formData, onChange, readonly, saveAction }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 列表管理
    const {
        list: trainList,
        remove: trainListRemove,
        push: trainListPush,
        getKey: trainListGetKey,
        resetList: trainListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        trainListReset(formData.trainList);
    }, [trainListReset, formData.trainList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('trainList', { initialValue: formData.trainList || [] });
    }, [formData.trainList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            employeeCode: formData.employeeCode,
            newList: trainList.map((item, index) => {
                const key = trainListGetKey(index);
                return {
                    startTime: values.startTime[key]?.[0]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    endTime: values.startTime[key]?.[1]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    // trainTime: values.trainTime[key] ? values.trainTime[key] : null, // 培训时长
                    trainContent: values.trainContent[key] ? values.trainContent[key] : null,
                    trainOrganize: values.trainOrganize[key] ? values.trainOrganize[key] : null,
                    certificate: values.certificate[key] ? values.certificate[key] : null
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        trainListReset(formData.trainList);
    };

    // 处理日期为空的情况
    const handleDealDateEmpty = (startDate, endDate) => {
        if (startDate === '' || endDate === '' || !startDate || !endDate) {
            return undefined;
        }
        return [moment(startDate), moment(endDate)];
    };

    // 很奇怪, 日期选择组件不能自动赋值
    const handleSetStartTimeValue = (values, keys) => {
        formRef.current.setFieldsValue({ [keys]: values });
    };

    // 取消编辑
    const handleEdit = () => {
        if (trainList.length === 0) {
            trainListPush({});
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="培训经历"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className={styles.dynamicList}>
                    {trainList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className={styles.dynamicListContainer}>
                        {trainList.map((item, index) => (
                            <div key={trainListGetKey(index)} className={styles.dynamicListItem}>
                                {editStatus && (
                                    <Icon
                                        onClick={() => trainListRemove(index)}
                                        className={styles.dynamicListClose}
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Row gutter={24}>
                                    <Col span={12}>
                                        <Form.Item label="起止时间">
                                            {editStatus
                                                ? getFieldDecorator(`startTime[${trainListGetKey(index)}]`, {
                                                    initialValue: handleDealDateEmpty(item?.startTime, item?.endTime)
                                                })(
                                                    <DatePicker.RangePicker
                                                        style={{ width: '100%' }}
                                                        format={RANGE_PICKER_FORMAT_YYYY_MM_DD}
                                                        onPanelChange={values =>
                                                            handleSetStartTimeValue(
                                                                values,
                                                                `startTime[${trainListGetKey(index)}]`
                                                            )
                                                        }
                                                    />
                                                )
                                                : formatDateRange(item?.startTime, item?.endTime, 'YYYY-MM-DD')}
                                        </Form.Item>
                                        <Form.Item label="证书">
                                            {editStatus ? (
                                                getFieldDecorator(`certificate[${trainListGetKey(index)}]`, {
                                                    initialValue: item?.certificate ?? undefined,
                                                    rules: [{ max: 50, message: '字数不能超过50个字符' }]
                                                })(<Input maxLength={50} placeholder="请输入证书" />)
                                            ) : (
                                                <div className="multiLineText">{item?.certificate}</div>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="培训主题/内容">
                                            {editStatus ? (
                                                getFieldDecorator(`trainContent[${trainListGetKey(index)}]`, {
                                                    initialValue: item?.trainContent ?? undefined,
                                                    rules: [{ max: 100, message: '字数不能超过100个字符' }]
                                                })(
                                                    <Input
                                                        maxLength={100}
                                                        placeholder="请输入培训主题/内容"
                                                    />
                                                )
                                            ) : (
                                                <div className="multiLineText">{item?.trainContent}</div>
                                            )}
                                        </Form.Item>
                                        <Form.Item label="培训机构">
                                            {editStatus ? (
                                                getFieldDecorator(`trainOrganize[${trainListGetKey(index)}]`, {
                                                    initialValue: item?.trainOrganize ?? undefined,
                                                    rules: [{ max: 100, message: '字数不能超过100个字符' }]
                                                })(<Input maxLength={100} placeholder="请输入培训机构" />)
                                            ) : (
                                                <div className="multiLineText">{item?.trainOrganize}</div>
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </div>
                        ))}
                    </div>
                    {editStatus && trainList.length < 10 ? (
                        <Button style={{ marginTop: '20px' }} block onClick={() => trainListPush({})}>
                            +添加培训经历
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
TrainingExperienceSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

TrainingExperienceSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default TrainingExperienceSection;
